package com.ytjj.qmyx.admin.service.channelProductService.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.RedisConstants;
import com.ytjj.common.enums.ProductStatusEnums;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.constants.SysConfigConstants;
import com.ytjj.common.constants.PlatformConstant;
import com.ytjj.qmyx.admin.dao.*;
import com.ytjj.qmyx.admin.dao.channel.ChannelLabelDao;
import com.ytjj.qmyx.admin.dao.channel.SalesChannelsManagementDao;
import com.ytjj.qmyx.admin.mapper.*;
import com.ytjj.qmyx.admin.model.ProductSelectDetailResponse;
import com.ytjj.qmyx.admin.model.*;
import com.ytjj.qmyx.admin.model.SalesChannelsManagement;
import com.ytjj.qmyx.admin.model.dto.RemoveProductDto;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.request.channel.ChannelProductSelectRequest;
import com.ytjj.qmyx.admin.model.response.*;
import com.ytjj.qmyx.admin.model.response.channel.ChannelProductDetailResponse;
import com.ytjj.qmyx.admin.model.response.goods.FreightTemplateResponse;
import com.ytjj.qmyx.admin.model.response.goods.ProductImgResponse;
import com.ytjj.qmyx.admin.model.response.goods.ProductSkuKeyResponse;
import com.ytjj.qmyx.admin.model.response.goods.ProductSkuValueResponse;
import com.ytjj.qmyx.admin.model.response.goods.*;
import com.ytjj.qmyx.admin.service.AdminService;
import com.ytjj.qmyx.admin.service.channelProductService.ChannelProductService;
import com.ytjj.qmyx.admin.service.channelProductService.FreightTemplateService;
import com.ytjj.qmyx.admin.utils.UserUtil;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.BankerRequest;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.BankerResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Lazy;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;

import static java.lang.Integer.parseInt;

/**
 * @Version: 1.0
 * <p>
 * 销售渠道商品接口
 */

@Service
@Slf4j
@RefreshScope
public class ChannelProductServiceImpl implements ChannelProductService {

    @Resource
    private ProductDao productDao;
    @Resource
    private ProductImgDao productImgDao;
    @Resource
    private ProductSpecDao productSpecDao;
    @Resource
    private ProductSkuValueDao productSkuValueDao;
    @Resource
    private ProductSkuKeyDao productSkuKeyDao;
    @Resource
    private ChannelLabelDao channelLabelDao;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductSpecMapper productSpecMapper;
    @Resource
    private GoodsDao goodsDao;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private ProductSkuValueMapper productSkuValueMapper;
    @Resource
    private ProductSkuKeyMapper productSkuKeyMapper;
    @Resource
    private ActivityColumnMapper activityColumnMapper;
    @Autowired
    private RedisService redisService;
    @Lazy
    @Autowired
    private AsyncServiceImpl asyncServiceImpl;
    @Resource
    private ProductCategoryMapper productCategoryMapper;
    @Resource
    private SupplyChainMsgMapper supplyChainMsgMapper;
    @Resource
    private ProductSubjectPlateMapper productSubjectPlateMapper;
    @Resource
    private ChannelProductLabelMapper channelProductLabelMapper;

    @Autowired
    private AdminService adminService;
    @Resource
    private SalesChannelsManagementMapper salesChannelsManagementMapper;
    @Resource
    private SalesChannelsManagementDao salesChannelsManagementDao;

    @Autowired
    private ProductCategoryDao productCategoryDao;
    @Value("${h5ShopId:GUOB004}")
    public String h5ShopId;
    @Value("${appShopId:GUOB005}")
    public String appShopId;
    @Value("${h5_2ShopId:GUOB006}")
    public String h5_2ShopId;
    @Value("${provinceShopId:GUOB008}")
    public String provinceShopId;
    @Value("${h5_3ShopId:GUOB007}")
    public String h5_3ShopId;
    @Autowired
    private FreightTemplateService freightTemplateService;
    @Value("${h5.default.template.id:152}")
    private Integer h5DefaultTemplateId;
    @Value("${app.default.template.id:151}")
    private Integer appDefaultTemplateId;

    /**
     * 受限制角色id(成本、供货价、供应商仓库地址)
     */
    @Value("${limit.roleId:2,13}")
    private String limitRoleId;

    @Resource(name = "guchuangRabbitTemplate")
    private RabbitTemplate guchuangRabbitTemplate;

//    @Resource(name = "jumaiduoRabbitTemplate")
//    private RabbitTemplate jumaiduoRabbitTemplate;

//    @Resource(name = "yiquanRabbitTemplate")
//    private RabbitTemplate yiquanRabbitTemplate;
//
//    @Resource(name = "zxlpRabbitTemplate")
//    private RabbitTemplate zxlpRabbitTemplate;
//
//    @Resource(name = "ygyxRabbitTemplate")
//    private RabbitTemplate ygyxRabbitTemplate;
//
//    @Resource(name = "yxhdRabbitTemplate")
//    private RabbitTemplate yxhdRabbitTemplate;
//
//    @Resource(name = "jckjRabbitTemplate")
//    private RabbitTemplate jckjRabbitTemplate;

    Executor pools = new ThreadPoolExecutor(5, 10, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024));

    @Override
    public CommonResult productChannelList(ProductChannelRequest request) {

        //判断供应链标签是否为空
        if (null != request.getSupplyProductLabelId()){
            //调用API查询使用该标签的商品id
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("productLabelId", request.getSupplyProductLabelId().toString());
            String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/getProductIdsByProductLabelId", paramMap, supplyApiConfig.getHeadsMap());
            List<Integer> productIds = JSONObject.parseArray(result, Integer.class);
            request.setSupplyProductIds(productIds);
        }

        if (!org.springframework.util.StringUtils.isEmpty(request.getBuyer())){
            BankerRequest request1 = new BankerRequest();
            request1.setBuyer(request.getBuyer());
            String json1 = JSON.toJSONString(request1);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/getBankerIdsByBankerMsg", json1, supplyApiConfig.getHeadsMap());
            List<Integer> bankerIds = JSONObject.parseArray(result, Integer.class);
            if (CollectionUtils.isEmpty(bankerIds)){
                return CommonResult.success(CommonPage.restPage(new ArrayList<>()));
            }
            request.setBankerIds(bankerIds);
        }

        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ProductChannelResponse> responses = productDao.getChannelProductList(request);


        if (!CollectionUtils.isEmpty(responses)) {
            //供应链商品标签
            List<Integer> supplyProductIds = responses.stream().filter(item ->null != item.getSupplyProductId()).map(ProductChannelResponse::getSupplyProductId).collect(Collectors.toList());
            SupplyProductLabelRequest supplyProductLabelRequest = new SupplyProductLabelRequest();
            supplyProductLabelRequest.setProductIds(supplyProductIds);
            String s = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getSupplyProductLabelByProductIds", JSONObject.toJSONString(supplyProductLabelRequest), supplyApiConfig.getHeadsMap());
            List<SupplyProductLabelResponse> supplyProductLabelResponses = JSONObject.parseArray(s, SupplyProductLabelResponse.class);

            List<YxProduct> yxProducts = new ArrayList<>();
            if (!CollectionUtils.isEmpty(supplyProductIds)){
                ProductReceiveRequest productReceiveRequest = new ProductReceiveRequest();
                productReceiveRequest.setProductIds(supplyProductIds);
                String json = JSON.toJSONString(productReceiveRequest);
                String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getByIds", json, supplyApiConfig.getHeadsMap());
                yxProducts = JSONObject.parseArray(result, YxProduct.class);
            }

            List<Integer> collect = responses.stream().map(ProductChannelResponse::getId).collect(Collectors.toList());
            //渠道标签
            List<ChannelLabel> channelLabelList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(collect)){
                channelLabelList = channelLabelDao.findByProductIds(request.getPlatformData(), collect);
            }
            //3.设置分类
            List<ProductCategory> allProductCategorys = this.getAllProductCategorys();

            List<Integer> bankerProductIds = responses.stream().map(ProductChannelResponse::getBankerProductId).collect(Collectors.toList());
            List<ProductSelectDetailResponse> productSelectDetails = new ArrayList<>();
            if (!CollectionUtils.isEmpty(allProductCategorys)){
                productSelectDetails = this.findProductSelectDetailByIds(Joiner.on(",").join(bankerProductIds));
            }
            //供应商id
            List<Integer> bankerIds = responses.stream().filter(item ->null != item.getBankerId()).map(ProductChannelResponse::getBankerId).collect(Collectors.toList());
            //查询供应商名称
            BankerRequest bankerRequest = new BankerRequest();
            bankerRequest.setBankerIdList(bankerIds);
            String json = JSON.toJSONString(bankerRequest);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", json, supplyApiConfig.getHeadsMap());
            List<BankerResponse> bankerResponses = JSONObject.parseArray(result, BankerResponse.class);

            //是否限制展示成本价和供货价角色
            boolean isLimitRole = checkIsLimitRole();

            for (ProductChannelResponse productChannelResponse : responses) {
                productChannelResponse.setPrice(productChannelResponse.getMinPrice());
                List<BankerResponse> bankerResponse = bankerResponses.stream().filter(banker -> banker.getBankerId().equals(productChannelResponse.getBankerId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(bankerResponse)){
                    //采购员
                    productChannelResponse.setBuyer(bankerResponse.get(0).getBuyer());
                }

                //商品供货价/总库存/售后地址
                List<YxProduct> collect1 = yxProducts.stream().filter(yxProduct -> yxProduct.getId().equals(productChannelResponse.getSupplyProductId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect1)){
                    productChannelResponse.setSupplyPrice(collect1.get(0).getSupplyPrice());
                    productChannelResponse.setStock(collect1.get(0).getStock());
                    //售后地址
                    productChannelResponse.setAddressInfo(collect1.get(0).getAddressInfo());
                    //品牌
                    productChannelResponse.setBrand(collect1.get(0).getBrand());
                }

                //供应链商品标签
                if (!CollectionUtils.isEmpty(supplyProductLabelResponses)){
                    List<SupplyProductLabelResponse> supplyProductLabelResponse = supplyProductLabelResponses.stream().filter(item -> item.getProductId().equals(productChannelResponse.getSupplyProductId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(supplyProductLabelResponse)){
                        productChannelResponse.setSupplyProductLabelName(supplyProductLabelResponse.get(0).getSupplyProductLabelName());
                    }
                }

                //1.渠道商品标签
                List<ChannelLabel> channelLabels  = channelLabelList.stream().filter(item -> item.getProductId().equals(productChannelResponse.getId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(channelLabels)) {
                    productChannelResponse.setChannelProductLabelList(channelLabels);
                }else {
                    productChannelResponse.setChannelProductLabelList(new ArrayList<>());
                }
                //2.总库存数
//                ProductSelectDetailResponse productSelectDetail = this.findProductSelectDetail(productChannelResponse.getId());
                ProductSelectDetailResponse productSelectDetail = null;
                List<ProductSelectDetailResponse> matchProductSelectDetails = productSelectDetails.stream().filter(item ->
                        item.getBankerProductId().equals(productChannelResponse.getBankerProductId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(matchProductSelectDetails)) {
                    productSelectDetail = matchProductSelectDetails.get(0);
                }
                log.debug("===productSelectDetail==={}", productSelectDetail);
                if (null == productSelectDetail) {
                    productChannelResponse.setStockSum(0);
                }else {
                    List<ProductSpecResponse> spec = productSelectDetail.getSpec();
                    Integer stock = 0;
                    log.debug("===spec==={}", spec);
                    for (ProductSpecResponse productSpecResponse : spec) {
                        stock += Optional.ofNullable(productSpecResponse.getStock()).orElse(0);
                    }
                    productChannelResponse.setStockSum(stock);
                }

                //一级标题
                Optional<ProductCategory> topCategory = allProductCategorys.stream().filter(e -> e.getId().equals(productChannelResponse.getTopCategoryId())).findFirst();
                //二级标题
                Optional<ProductCategory> category = allProductCategorys.stream().filter(e -> e.getId().equals(productChannelResponse.getCategoryId())).findFirst();
                //三级标题
                Optional<ProductCategory> bottomCategory = allProductCategorys.stream().filter(e -> e.getId().equals(productChannelResponse.getBottomCategoryId())).findFirst();
                productChannelResponse.setTopCategoryTitle(topCategory.isPresent() ? topCategory.get().getTitle() : "");
                productChannelResponse.setCategoryTitle(category.isPresent() ? category.get().getTitle() : "");
                productChannelResponse.setBottomCategoryTitle(bottomCategory.isPresent() ? bottomCategory.get().getTitle() : "");

                // 毛利率 (售价减供货价)除以售价乘以100
                BigDecimal price = null == productChannelResponse.getPrice() ? BigDecimal.ZERO : productChannelResponse.getPrice();
                BigDecimal costPrice = null == productChannelResponse.getSupplyPrice() ? BigDecimal.ZERO : productChannelResponse.getSupplyPrice();
                BigDecimal grossProfit = new BigDecimal(0);
                String grossProfixRate = "0.00";
                if (price.compareTo(BigDecimal.ZERO) != 0 && price != null) {
                    grossProfit = price.subtract(costPrice).divide(price, 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                    DecimalFormat df = new DecimalFormat("0.00");
                    grossProfixRate = df.format(grossProfit);
                }
                productChannelResponse.setGrossProfitRate(grossProfixRate);

                if (isLimitRole) {
                    productChannelResponse.setSupplyPrice(BigDecimal.ZERO);
                    productChannelResponse.setGrossProfitRate("--");
                }
                // 补贴力度
                BigDecimal subsidy = null == productChannelResponse.getOriginalPrice() ? BigDecimal.ZERO :
                        productChannelResponse.getOriginalPrice().subtract(Optional.ofNullable(productChannelResponse.getPrice()).orElse(BigDecimal.ZERO));
                productChannelResponse.setSubsidy(subsidy.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : subsidy);

                //解析活动栏目
                String activityColumnName="";
                String activityColumnIds=productChannelResponse.getActivityColumnIds();
                List<Integer> activityColumnIdList = new ArrayList<>();
                if(org.apache.commons.lang3.StringUtils.isNotBlank(activityColumnIds)){
                    try {
                        String[] activityColumnIdArray = activityColumnIds.split(",");
                        ActivityColumnExample example = new ActivityColumnExample();
                        activityColumnIdList = Arrays.asList(activityColumnIdArray).stream().map(Integer::parseInt).collect(Collectors.toList());
                        example.createCriteria().andIdIn(activityColumnIdList);
                        List<ActivityColumn> activityColumns = activityColumnMapper.selectByExample(example);

                        if (!CollectionUtils.isEmpty(activityColumns)) {
                            activityColumnName = String.join(",", activityColumns.stream().map(ActivityColumn::getTitle).collect(Collectors.toList()));
                        }
                    }catch (Exception e){
                        log.error("解析活动栏目id错误",e);
                    }
                    productChannelResponse.setActivityColumnName(activityColumnName);
                }else{
                    productChannelResponse.setActivityColumnName("");
                }
            }
        }
        return CommonResult.success(CommonPage.restPage(responses));
    }

    @Override
    public List<ProductChannelResponse> productChannelListForArea(ProductChannelRequest request) {
        //判断供应链标签是否为空
        if (null != request.getSupplyProductLabelId()) {
            //调用API查询使用该标签的商品id
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("productLabelId", request.getSupplyProductLabelId().toString());
            String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/getProductIdsByProductLabelId", paramMap, supplyApiConfig.getHeadsMap());
            List<Integer> productIds = JSONObject.parseArray(result, Integer.class);
            request.setSupplyProductIds(productIds);
        }

        if (!org.springframework.util.StringUtils.isEmpty(request.getBuyer())) {
            BankerRequest request1 = new BankerRequest();
            request1.setBuyer(request.getBuyer());
            String json1 = JSON.toJSONString(request1);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/banker/getBankerIdsByBankerMsg", json1, supplyApiConfig.getHeadsMap());
            List<Integer> bankerIds = JSONObject.parseArray(result, Integer.class);
            if (CollectionUtils.isEmpty(bankerIds)) {
                return new ArrayList<>();
            }
            request.setBankerIds(bankerIds);
        }

        List<String> provinceCodes = request.getProvinceCodes();
        if (PlatformConstant.PROVINCE_PLATFORM.equals(request.getPlatformData())) {
            if (!CollectionUtils.isEmpty(provinceCodes)) {
                List<String> collect = provinceCodes.stream().map(e -> PlatformConstant.PROVINCE_PLATFORM + e).collect(Collectors.toList());
                provinceCodes = collect;
            }
            request.setProvinceCodes(provinceCodes);
        }
        List<ProductChannelResponse> responses = productDao.getChannelProductListForArea(request);

        if (!CollectionUtils.isEmpty(responses)) {
            //供应链商品标签
            List<Integer> supplyProductIds = responses.stream().filter(item -> null != item.getSupplyProductId()).map(ProductChannelResponse::getSupplyProductId).collect(Collectors.toList());
            SupplyProductLabelRequest supplyProductLabelRequest = new SupplyProductLabelRequest();
            supplyProductLabelRequest.setProductIds(supplyProductIds);
            String s = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getSupplyProductLabelByProductIds", JSONObject.toJSONString(supplyProductLabelRequest), supplyApiConfig.getHeadsMap());
            List<SupplyProductLabelResponse> supplyProductLabelResponses = JSONObject.parseArray(s, SupplyProductLabelResponse.class);

            List<YxProduct> yxProducts = new ArrayList<>();
            if (!CollectionUtils.isEmpty(supplyProductIds)) {
                ProductReceiveRequest productReceiveRequest = new ProductReceiveRequest();
                productReceiveRequest.setProductIds(supplyProductIds);
                String json = JSON.toJSONString(productReceiveRequest);
                String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getByIds", json, supplyApiConfig.getHeadsMap());
                yxProducts = JSONObject.parseArray(result, YxProduct.class);
            }

            List<Integer> collect = responses.stream().map(ProductChannelResponse::getId).collect(Collectors.toList());
            //渠道标签
            List<ChannelLabel> channelLabelList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(collect)) {
                channelLabelList = channelLabelDao.findByProductIds(request.getPlatformData(), collect);
            }
            //3.设置分类
            List<ProductCategory> allProductCategorys = this.getAllProductCategorys();

            List<Integer> bankerProductIds = responses.stream().map(ProductChannelResponse::getBankerProductId).collect(Collectors.toList());
            List<ProductSelectDetailResponse> productSelectDetails = new ArrayList<>();
            if (!CollectionUtils.isEmpty(allProductCategorys)) {
                productSelectDetails = this.findProductSelectDetailByIds(Joiner.on(",").join(bankerProductIds));
            }
            //供应商id
            List<Integer> bankerIds = responses.stream().filter(item -> null != item.getBankerId()).map(ProductChannelResponse::getBankerId).collect(Collectors.toList());
            //查询供应商名称
            BankerRequest bankerRequest = new BankerRequest();
            bankerRequest.setBankerIdList(bankerIds);
            String json = JSON.toJSONString(bankerRequest);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getBankerMsg", json, supplyApiConfig.getHeadsMap());
            List<BankerResponse> bankerResponses = JSONObject.parseArray(result, BankerResponse.class);
            //地区销售渠道
            Map<String, List<SalesChannelsManagement>> saleMap = new HashMap<>();
            if (PlatformConstant.PROVINCE_PLATFORM.equals(request.getPlatformData())) {
                List<SalesChannelsManagement> salesChannelsManagements = salesChannelsManagementDao.getAllSalesChannels(null);
                if (!CollectionUtils.isEmpty(salesChannelsManagements)) {
                    saleMap = salesChannelsManagements.stream().collect(Collectors.groupingBy(e -> {
                        String code = "";
                        if (e.getType() == 3) {
                            code = PlatformConstant.PROVINCE_PLATFORM + e.getCode();
                        } else {
                            code = e.getCode();
                        }
                        return code;
                    }));
                }
            }
            //是否限制展示成本价和供货价角色
            boolean isLimitRole = checkIsLimitRole();

            for (ProductChannelResponse productChannelResponse : responses) {
                //设置地区
                String platformData = productChannelResponse.getPlatformData();
                if (PlatformConstant.PROVINCE_PLATFORM.equals(request.getPlatformData()) && !CollectionUtils.isEmpty(saleMap)) {
                    List<SalesChannelsManagement> salesChannelsManagements = saleMap.get(productChannelResponse.getPlatformData());
                    if (!CollectionUtils.isEmpty(salesChannelsManagements)) {
                        String name = salesChannelsManagements.get(0).getName();
                        if (!StringUtils.isEmpty(name) && PlatformConstant.PROVINCE_PLATFORM.equals(name)) {
                            productChannelResponse.setPlatformText("");
                        } else {
                            productChannelResponse.setPlatformText(name);
                        }
                    }
                }
                productChannelResponse.setPrice(productChannelResponse.getMinPrice());
                List<BankerResponse> bankerResponse = bankerResponses.stream().filter(banker -> banker.getBankerId().equals(productChannelResponse.getBankerId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(bankerResponse)) {
                    //采购员
                    productChannelResponse.setBuyer(bankerResponse.get(0).getBuyer());
                }

                //商品供货价/总库存/售后地址
                List<YxProduct> collect1 = yxProducts.stream().filter(yxProduct -> yxProduct.getId().equals(productChannelResponse.getSupplyProductId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(collect1)) {
                    productChannelResponse.setSupplyPrice(collect1.get(0).getSupplyPrice());
                    productChannelResponse.setStock(collect1.get(0).getStock());
                    //售后地址
                    productChannelResponse.setAddressInfo(collect1.get(0).getAddressInfo());
                    //品牌
                    productChannelResponse.setBrand(collect1.get(0).getBrand());
                }

                //供应链商品标签
                if (!CollectionUtils.isEmpty(supplyProductLabelResponses)) {
                    List<SupplyProductLabelResponse> supplyProductLabelResponse = supplyProductLabelResponses.stream().filter(item -> item.getProductId().equals(productChannelResponse.getSupplyProductId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(supplyProductLabelResponse)) {
                        productChannelResponse.setSupplyProductLabelName(supplyProductLabelResponse.get(0).getSupplyProductLabelName());
                    }
                }

                //1.渠道商品标签
                List<ChannelLabel> channelLabels = channelLabelList.stream().filter(item -> item.getProductId().equals(productChannelResponse.getId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(channelLabels)) {
                    productChannelResponse.setChannelProductLabelList(channelLabels);
                } else {
                    productChannelResponse.setChannelProductLabelList(new ArrayList<>());
                }
                //2.总库存数
//                ProductSelectDetailResponse productSelectDetail = this.findProductSelectDetail(productChannelResponse.getId());
                ProductSelectDetailResponse productSelectDetail = null;
                List<ProductSelectDetailResponse> matchProductSelectDetails = productSelectDetails.stream().filter(item ->
                        item.getBankerProductId().equals(productChannelResponse.getBankerProductId())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(matchProductSelectDetails)) {
                    productSelectDetail = matchProductSelectDetails.get(0);
                }
                log.debug("===productSelectDetail==={}", productSelectDetail);
                if (null == productSelectDetail) {
                    productChannelResponse.setStockSum(0);
                } else {
                    List<ProductSpecResponse> spec = productSelectDetail.getSpec();
                    Integer stock = 0;
                    log.debug("===spec==={}", spec);
                    for (ProductSpecResponse productSpecResponse : spec) {
                        stock += Optional.ofNullable(productSpecResponse.getStock()).orElse(0);
                    }
                    productChannelResponse.setStockSum(stock);
                }

                //一级标题
                Optional<ProductCategory> topCategory = allProductCategorys.stream().filter(e -> e.getId().equals(productChannelResponse.getTopCategoryId())).findFirst();
                //二级标题
                Optional<ProductCategory> category = allProductCategorys.stream().filter(e -> e.getId().equals(productChannelResponse.getCategoryId())).findFirst();
                //三级标题
                Optional<ProductCategory> bottomCategory = allProductCategorys.stream().filter(e -> e.getId().equals(productChannelResponse.getBottomCategoryId())).findFirst();
                productChannelResponse.setTopCategoryTitle(topCategory.isPresent() ? topCategory.get().getTitle() : "");
                productChannelResponse.setCategoryTitle(category.isPresent() ? category.get().getTitle() : "");
                productChannelResponse.setBottomCategoryTitle(bottomCategory.isPresent() ? bottomCategory.get().getTitle() : "");

                // 毛利率 (售价减供货价)除以售价乘以100
                BigDecimal price = null == productChannelResponse.getPrice() ? BigDecimal.ZERO : productChannelResponse.getPrice();
                BigDecimal costPrice = null == productChannelResponse.getSupplyPrice() ? BigDecimal.ZERO : productChannelResponse.getSupplyPrice();
                BigDecimal grossProfit = new BigDecimal(0);
                String grossProfixRate = "0.00";
                if (price.compareTo(BigDecimal.ZERO) != 0 && price != null) {
                    grossProfit = price.subtract(costPrice).divide(price, 4, BigDecimal.ROUND_DOWN).multiply(new BigDecimal(100));
                    DecimalFormat df = new DecimalFormat("0.00");
                    grossProfixRate = df.format(grossProfit);
                }
                productChannelResponse.setGrossProfitRate(grossProfixRate);

                if (isLimitRole) {
                    productChannelResponse.setSupplyPrice(BigDecimal.ZERO);
                    productChannelResponse.setGrossProfitRate("--");
                }
                // 补贴力度
                BigDecimal subsidy = null == productChannelResponse.getOriginalPrice() ? BigDecimal.ZERO :
                        productChannelResponse.getOriginalPrice().subtract(Optional.ofNullable(productChannelResponse.getPrice()).orElse(BigDecimal.ZERO));
                productChannelResponse.setSubsidy(subsidy.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : subsidy);

                //解析活动栏目
                String activityColumnName = "";
                String activityColumnIds = productChannelResponse.getActivityColumnIds();
                List<Integer> activityColumnIdList = new ArrayList<>();
                if (org.apache.commons.lang3.StringUtils.isNotBlank(activityColumnIds)) {
                    try {
                        String[] activityColumnIdArray = activityColumnIds.split(",");
                        ActivityColumnExample example = new ActivityColumnExample();
                        activityColumnIdList = Arrays.asList(activityColumnIdArray).stream().map(Integer::parseInt).collect(Collectors.toList());
                        example.createCriteria().andIdIn(activityColumnIdList);
                        List<ActivityColumn> activityColumns = activityColumnMapper.selectByExample(example);

                        if (!CollectionUtils.isEmpty(activityColumns)) {
                            activityColumnName = String.join(",", activityColumns.stream().map(ActivityColumn::getTitle).collect(Collectors.toList()));
                        }
                    } catch (Exception e) {
                        log.error("解析活动栏目id错误", e);
                    }
                    productChannelResponse.setActivityColumnName(activityColumnName);
                } else {
                    productChannelResponse.setActivityColumnName("");
                }
            }
        }
        return responses;
    }

    @Override
    public CommonResult areaProductChannelList(ProductChannelRequest request) {
        List<AreaProductChannelResponse> result = new ArrayList<>();
        ProductChannelRequest parentRequest = new ProductChannelRequest();
        BeanUtils.copyProperties(request, parentRequest);
        //查询主商品
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<ProductChannelResponse> mainProduct = productDao.getAreaMainProductList(request);
        if (CollectionUtils.isEmpty(mainProduct)) {
            return CommonResult.success(new ArrayList<>());
        }
        CommonPage<ProductChannelResponse> productPage = CommonPage.restPage(mainProduct);
        ProductChannelRequest newRequest = new ProductChannelRequest();
        newRequest.setSupplyProductIds(mainProduct.stream().map(e -> e.getSupplyProductId()).collect(Collectors.toList()));
        newRequest.setPlatformData("province");
        //查询主商品明细
        List<ProductChannelResponse> list = this.productChannelListForArea(newRequest);
        if (!CollectionUtils.isEmpty(list)) {
            List<String> provinceCodes = new ArrayList<>();
            //查询条件没有有选择查地区，则查所有地区。否则根据选择的地区查询
            if (CollectionUtils.isEmpty(request.getProvinceCodes())) {
                SalesChannelsManagement saleRequest = new SalesChannelsManagement();
                saleRequest.setType(3);
                List<SalesChannelsManagement> allSalesChannels = salesChannelsManagementDao.getAllSalesChannels(saleRequest);
                for (SalesChannelsManagement allSalesChannel : allSalesChannels) {
                    provinceCodes.add(allSalesChannel.getCode());
                }
            } else {
                provinceCodes = request.getProvinceCodes();
            }
            List<ProductChannelResponse> productChannelResponses = JSON.parseArray(JSON.toJSONString(list), ProductChannelResponse.class);
            CountDownLatch countDownLatch = new CountDownLatch(list.size());
            List<String> finalProvinceCodes = provinceCodes;
            //是否限制展示成本价和供货价角色
            boolean isLimitRole = checkIsLimitRole();
            //查询主商品下面的子商品
            productChannelResponses.stream().forEach(item -> {
                pools.execute(() -> {
                    try {
                        AreaProductChannelResponse areaProductChannelResponse = new AreaProductChannelResponse();
                        BeanUtils.copyProperties(item, areaProductChannelResponse);
                        ProductChannelRequest itemRequest = new ProductChannelRequest();
                        BeanUtils.copyProperties(request, itemRequest);
                        itemRequest.setSupplyProductId(item.getSupplyProductId());
                        itemRequest.setProvinceCodes(finalProvinceCodes);
                        if (null != request.getProductId()) {
                            itemRequest.setProductId(request.getProductId());
                        }
                        //2.查询每条province渠道的商品投放的地区商品
                        itemRequest.setMark(2);
                        List<ProductChannelResponse> childResult = this.productChannelListForArea(itemRequest);
                        if (!CollectionUtils.isEmpty(childResult)) {
                            List<ProductChannelResponse> collect = childResult.stream().filter(e -> !PlatformConstant.PROVINCE_PLATFORM.equals(e.getPlatformData())).collect(Collectors.toList());
                            collect.forEach(e->{
                                if (isLimitRole) {
                                    e.setSupplyPrice(BigDecimal.ZERO);
                                    e.setGrossProfitRate("--");
                                }
                            });
                            areaProductChannelResponse.setChildren(CollectionUtils.isEmpty(collect) ? new ArrayList<>() : collect);
                        } else {
                            areaProductChannelResponse.setChildren(new ArrayList<>());
                        }
                        result.add(areaProductChannelResponse);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            });
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //重新排序
            List<AreaProductChannelResponse> collect = result.stream().sorted(Comparator.comparing(AreaProductChannelResponse::getId, Comparator.reverseOrder())).collect(Collectors.toList());
            CommonPage<AreaProductChannelResponse> areaProductCommonPage = CommonPage.restPage(collect);
            areaProductCommonPage.setTotal(productPage.getTotal());
            areaProductCommonPage.setTotalPage(productPage.getTotalPage());
            areaProductCommonPage.setPageNum(productPage.getPageNum());
            areaProductCommonPage.setPageSize(productPage.getPageSize());
            return CommonResult.success(areaProductCommonPage);
        } else {
            return CommonResult.success(new ArrayList<>());
        }
    }

    @Override
    public boolean checkIsLimitRole() {
        boolean isLimitRole = false;
        try {
            String userId = UserUtil.getPrincipal();
            List<Role> role = adminService.getRoleByEmail(userId);
            log.info("====currentUserRoldId={}", role.toString());
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(role) && !com.alibaba.excel.util.StringUtils.isEmpty(limitRoleId)) {
                List<String> limitRoleIds = Arrays.asList(limitRoleId.split(","));
                if (limitRoleIds.contains(String.valueOf(role.get(0).getId()))) {
                    isLimitRole = true;
                }
            }
        } catch (Exception e) {
            log.error("{}", e);
        }
        return isLimitRole;
    }


    @Override
    public CommonResult removeProduct(Integer productChannelId) {
        Product product = new Product();
        product.setId(productChannelId);
        product.setStatus((byte) 3);
        productMapper.updateByPrimaryKeySelective(product);
        Product product1 = productMapper.selectByPrimaryKey(productChannelId);
        RemoveProductDto removeProductDto = new RemoveProductDto();
        List<Integer> ids = new ArrayList<>();
        ids.add(product1.getSupplyProductId());
        removeProductDto.setProductIds(ids);
        removeProductDto.setShopId(appShopId);
        String platformData = product1.getPlatformData();
        if (platformData != null && PlatformConstant.H5_2_PLATFORM.equalsIgnoreCase(platformData)) {
            removeProductDto.setShopId(h5_2ShopId);
        }
        if (platformData!=null && PlatformConstant.H5_3_PLATFORM.equalsIgnoreCase(platformData)){
            removeProductDto.setShopId(h5_3ShopId);
        }
        removeProductDto.setStatus("0");
        String json = JSON.toJSONString(removeProductDto);
        String doPostJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/remove", json, supplyApiConfig.getHeadsMap());
        CommonResult result = JSONObject.parseObject(doPostJson, CommonResult.class);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CommonResult removeProductFromArea(Integer productChannelId, Integer isMain) {
        Product product = productMapper.selectByPrimaryKey(productChannelId);
        if (null == product) {
            throw new ApiException("商品不存在！");
        }
        //移除主商品
        if (isMain != null && isMain == 1) {
            SalesChannelsManagement request = new SalesChannelsManagement();
            request.setType(3);
            List<SalesChannelsManagement> allSalesChannels = salesChannelsManagementDao.getAllSalesChannels(request);
            List<String> platforms = new ArrayList<>();
            for (SalesChannelsManagement allSalesChannel : allSalesChannels) {
                platforms.add(PlatformConstant.PROVINCE_PLATFORM + allSalesChannel.getCode());
            }
            platforms.add(PlatformConstant.PROVINCE_PLATFORM);
            List<Product> productList = productDao.queryBySupplyIdAndPlatformData(Arrays.asList(product.getSupplyProductId()), platforms);
            List<Product> collect = productList.stream().filter(e -> 1 == e.getStatus() && !PlatformConstant.PROVINCE_PLATFORM.equals(e.getPlatformData())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                throw new ApiException("存在未下架商品，请先全部下架再移除！");
            }
            for (Product item : productList) {
                Product newEntity = new Product();
                newEntity.setId(item.getId());
                newEntity.setStatus((byte) 3);
                productMapper.updateByPrimaryKeySelective(newEntity);
            }

            RemoveProductDto removeProductDto = new RemoveProductDto();
            List<Integer> ids = new ArrayList<>();
            ids.add(product.getSupplyProductId());
            removeProductDto.setProductIds(ids);
            removeProductDto.setShopId(provinceShopId);
            removeProductDto.setStatus("0");
            String json = JSON.toJSONString(removeProductDto);
            String doPostJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/remove", json, supplyApiConfig.getHeadsMap());
            CommonResult result = JSONObject.parseObject(doPostJson, CommonResult.class);
            if (null == result || 200 != result.getCode()) {
                throw new ApiException("移除失败，供应链接口出错：" + result.getMessage());
            }
            return result;
        } else {//移除子商品
            if(PlatformConstant.PROVINCE_PLATFORM.equals(product.getPlatformData())){
                throw new ApiException("isMain请求参数错误！");
            }
            Product newEntity = new Product();
            newEntity.setId(productChannelId);
            newEntity.setStatus((byte) 3);
            int i = productMapper.updateByPrimaryKeySelective(newEntity);
            return i > 0 ? CommonResult.success() : CommonResult.failed();
        }
    }

    @Override
    public CommonResult removeH5Product(Integer productChannelId) {
        Product product = new Product();
        product.setId(productChannelId);
        product.setStatus((byte) 3);
        productMapper.updateByPrimaryKeySelective(product);
        Product product1 = productMapper.selectByPrimaryKey(productChannelId);
        RemoveProductDto removeProductDto = new RemoveProductDto();
        List<Integer> ids = new ArrayList<>();
        ids.add(product1.getSupplyProductId());
        removeProductDto.setProductIds(ids);
        if (null != product1.getPlatformData() && product1.getPlatformData().equalsIgnoreCase(PlatformConstant.PLATFORM_H5)) {
            removeProductDto.setShopId(h5ShopId);
        } else {
            removeProductDto.setShopId(appShopId);
        }
        removeProductDto.setStatus("0");
        String json = JSON.toJSONString(removeProductDto);
        String doPostJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/remove", json, supplyApiConfig.getHeadsMap());
        CommonResult result = JSONObject.parseObject(doPostJson, CommonResult.class);
        return result;
    }

    @Override
    public CommonResult getProductChannelInfo(Integer productId) {
        ChannelProductDetailResponse response = productDao.getChannelProductDetailApp(productId);
        //销量字段
        if (StringUtils.isEmpty(response.getVolumeStr())) {
            Integer v = new Random().nextInt(2000) + 8000;
            response.setVolumeStr(String.valueOf(v));
            response.setVolume(v);
        }
        //好评率
        if (null == response.getGoodRatio()) {
            Integer v = new Random().nextInt(2) + 97;
            response.setGoodRatio(v);
        }
        //评论总数
        if (null == response.getCommentSum()) {
            Integer v = new Random().nextInt(1200) + 800;
            response.setCommentSum(v);
        }
        //点击量
        if (null == response.getPv() || 0 == response.getPv()) {
            response.setPv(Integer.valueOf(response.getVolumeStr()) * 2);
        }
        //排序
        if (null == response.getSort()) {
            response.setSort(123);
        }

        List<ProductSkuKeyResponse> skuKey = goodsDao.findSku(productId);
        List<ProductImgResponse> bannerList = goodsDao.findImgApp(productId, "banner");
        List<ProductImgResponse> infoList = goodsDao.findImgApp(productId, "info");
        List<ProductSpecResponse> spec = goodsDao.findSpecApp(productId);

        //是否限制展示成本价和供货价角色
        boolean isLimitRole = checkIsLimitRole();
        for (ProductSpecResponse item : spec) {
            if (isLimitRole) {
                item.setCostPrice(BigDecimal.ZERO);
                item.setSupplyPrice(BigDecimal.ZERO);
            }
        }

        String addressId = "";
        try {
            if (null != response) {
                Map<String, String> map = new HashMap<>();
                map.put("productId", String.valueOf(response.getSupplyProductId()));
                addressId = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/getAddressId", map, supplyApiConfig.getHeadsMap());
                log.info("=========获取售后地址===========addressId{}", addressId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setAddressId(org.apache.commons.lang3.StringUtils.isNotBlank(addressId) ? Integer.valueOf(addressId) : null);
        //获取规格库存
        List<Integer> supplyIds = spec.stream().filter(item -> null != item.getSupplyId()).map(ProductSpecResponse::getSupplyId).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(supplyIds)) {
            ProductSpecStockQureyRequest productSpecStockQureyRequest = new ProductSpecStockQureyRequest();
            productSpecStockQureyRequest.setSupplyIds(supplyIds);
            String json = JSON.toJSONString(productSpecStockQureyRequest);
            String doPostJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/getSpecStock", json, supplyApiConfig.getHeadsMap());
            if (!StringUtils.isEmpty(doPostJson)) {
                List<ProductSpecStockQureyResponse> productSpecStockQureyResponses = JSONObject.parseArray(doPostJson, ProductSpecStockQureyResponse.class);
                spec.stream().forEach(item -> {
                    List<ProductSpecStockQureyResponse> collect = productSpecStockQureyResponses.stream().filter(productSpecStockQureyResponse -> productSpecStockQureyResponse.getSupplyId().equals(item.getSupplyId())).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(collect)) {
                        ProductSpecStockQureyResponse productSpecStockQureyResponse = collect.get(0);
                        item.setStock(productSpecStockQureyResponse.getStock());
                    }
                });
            }
        }

        response.setSkuKey(skuKey);
        response.setBannerList(bannerList);
        response.setInfoList(infoList);
        response.setSpec(spec);

        HashMap<String, String> map = new HashMap<>();
        map.put("id", String.valueOf(response.getSupplyProductId()));
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/findProductSelectDetail", map, supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            return null;
        }
        JSONObject parse = JSON.parseObject(resultJson);
        ProductSelectDetailResponse supplyResponseData = JSONObject.parseObject(parse.getString("data"), ProductSelectDetailResponse.class);
        FreightTemplateResponse freightTemplateResponse = freightTemplateService.selectFreightTemplateResponse(response.getFreightId());
        FreightTemplateResponse defaultFreightTemplate = freightTemplateService.selectDefaultFreightTemplate(response.getPlatformData());
        if (null != supplyResponseData) {
            response.setFreightTemplateResponse(freightTemplateResponse == null ? defaultFreightTemplate : freightTemplateResponse);
            response.setTypeno(supplyResponseData.getTypeno());
            response.setControlPrice(supplyResponseData.getControlPrice());
            response.setControlReason(supplyResponseData.getControlReason());
            response.setControlReason(supplyResponseData.getControlReason());
            response.setSupplyFreightId(supplyResponseData.getFreightId() == null ? 0 : supplyResponseData.getFreightId());
            response.setSupplyFreightTemplateResponse(supplyResponseData.getFreightTemplateResponse());
            //品牌
            response.setBrand(supplyResponseData.getBrand());
            response.setBrandId(supplyResponseData.getBrandId());
        }
        return CommonResult.success(response);
    }


    @Override
    public CommonResult putOutChannelProduct(Integer productChannelId, Integer status, String outRemarks) {
        //上架
        if (status.compareTo(1) == 0) {
            //验证商品信息是否完整
            Product channelProductApp = productMapper.selectByPrimaryKey(productChannelId);
            //判断供应链商品是否上架
            getSupplyProductStatus(channelProductApp);

//            if (null == channelProductApp.getOriginalPrice() || channelProductApp.getOriginalPrice().compareTo(new BigDecimal(0)) == 0) {
//                throw new ApiException("请补充商品信息");
//            }

            //验证商品规格是否完整
            ProductSpecExample productSpecExample = new ProductSpecExample();
            productSpecExample.createCriteria().andProductIdEqualTo(channelProductApp.getId());
            List<ProductSpec> productSpecs = productSpecMapper.selectByExample(productSpecExample);
            //检查供应链商品规格是否被修改
            List<Integer> supplyIds = productSpecs.stream().filter(spec -> null != spec.getSupplyId()).map(ProductSpec::getSupplyId).collect(Collectors.toList());
            ProductRequest productRequest = new ProductRequest();
            productRequest.setSupplyProductId(channelProductApp.getSupplyProductId());
            productRequest.setSupplyIds(supplyIds);
            String json = JSON.toJSONString(productRequest);
            String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/checkSpec", json, supplyApiConfig.getHeadsMap());
            if (null != resultJson && "true".equals(resultJson)) {
                throw new ApiException("供应链商品规格有增加或删除,请移除商品后,重新选品");
            }

            productSpecs.stream().forEach(item -> {
                ProductSpecExample channelProductSpecExample = new ProductSpecExample();
                channelProductSpecExample.createCriteria().andProductIdEqualTo(productChannelId).andIdEqualTo(item.getId());
                List<ProductSpec> channelProductSpecs = productSpecMapper.selectByExample(channelProductSpecExample);
                if (CollectionUtils.isEmpty(channelProductSpecs)) {
                    throw new ApiException("请补充商品信息");
                }
                ProductSpec channelProductSpec = channelProductSpecs.get(0);
                if (null == channelProductSpec.getCurPrice() || channelProductSpec.getCurPrice() == new BigDecimal(0)) {
                    throw new ApiException("请补充商品信息");
                }
                if (null == channelProductSpec.getPrice() || channelProductSpec.getPrice() == new BigDecimal(0)) {
                    throw new ApiException("请补充商品信息");
                }
            });

            Product channelProduct = new Product();
            channelProduct.setId(productChannelId);
            channelProduct.setStatus(status.byteValue());
            channelProduct.setDownRemark("");
            channelProduct.setUpdateTime(new Date());
            productMapper.updateByPrimaryKeySelective(channelProduct);
            return CommonResult.success("商品上架成功");

            //下架
        } else if (status.compareTo(2) == 0) {
            Product channelProduct = new Product();
            channelProduct.setId(productChannelId);
            channelProduct.setStatus(status.byteValue());
            channelProduct.setDownRemark(outRemarks);
            channelProduct.setUpdateTime(new Date());
            productMapper.updateByPrimaryKeySelective(channelProduct);
            return CommonResult.success("商品下架成功");
        }
        return CommonResult.failed();
    }

    @Override
    public PutOutProductResp batchPutOutChannelProduct(List<Product> products, Integer status) {
        PutOutProductResp putOutProductResp = new PutOutProductResp();
        List<Product> successProduts = Lists.newArrayList();
        List<Product> failProduts = Lists.newArrayList();
        for (Product product : products) {
            try {
                putOutChannelProduct(product.getId(), status, product.getDownRemark());
                Product successProduct = new Product();
                successProduct.setId(product.getId());
                successProduct.setProductName(product.getProductName());
                successProduts.add(successProduct);
            } catch (Exception e) {
                Product failProduct = new Product();
                failProduct.setId(product.getId());
                failProduct.setProductName(product.getProductName());
                failProduct.setFailRemark(e.getMessage());
                failProduts.add(failProduct);
            }
        }
        putOutProductResp.setTotalNum(products.size());
        putOutProductResp.setSuccessNum(successProduts.size());
        putOutProductResp.setFailNum(failProduts.size());
        putOutProductResp.setSuccessProduts(successProduts);
        putOutProductResp.setFailProduts(failProduts);
        return putOutProductResp;
    }

    private void recordProductDownMessage(Integer productId, Integer type, String message) {
        log.info("===供应链商品下架记录日志：{}，{}，{}===", productId, type, message);
        SupplyChainMsg msg = new SupplyChainMsg();
        msg.setProductid(productId);
        msg.setType(type);
        msg.setMsg(message);
        msg.setStatus(0);
        msg.setCreateTime(new Date());
        supplyChainMsgMapper.insert(msg);
    }

    @Override
    public void getSupplyProductStatus(Product channelProduct) {
        Map<String, String> map = new LinkedMap();
        map.put("bankerProductId", String.valueOf(channelProduct.getBankerProductId()));
        log.info("=============/stock/get=====================参数{}", map);
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/stock/get", map, supplyApiConfig.getHeadsMap());
        log.info("=============/stock/get=====================返回{}", resultJson);
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        if (200 != commonResult.getCode()) {
            throw new ApiException("商品信息异常");
        }
        ProductStockAndSpecResponse response = JSONObject.parseObject(commonResult.getData().toString(), ProductStockAndSpecResponse.class);
        log.info("===response==={}", response);
        if (response.getStatus() != 1) {
            throw new ApiException("供应链商品未上架");
        }
    }

    @Override
    public CommonResult findProduceSelect(ChannelProductSelectRequest productRequest) {
        productRequest.setShopId(supplyApiConfig.getShopId());
        if (2 == productRequest.getChannel()) {
            productRequest.setShopId(appShopId);
        }
        if (3 == productRequest.getChannel()) {
            productRequest.setShopId(h5_2ShopId);
        }
        if (4 == productRequest.getChannel()) {
            productRequest.setShopId(provinceShopId);
        }
        if (5 == productRequest.getChannel()){
            productRequest.setShopId(h5_3ShopId);
        }
        String json = JSON.toJSONString(productRequest);
        log.info("查询选品中心商品参数:{}", json);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/findProduceSelect", json, supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            return null;
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        return result;
    }

    @Override
    public List<ProductCategory> getAllProductCategorys() {
        List<ProductCategory> productCategoryAllList = null;
        String categoryListRedisVal = redisService.get(RedisConstants.SUPPLY_CHAIN_PRODUCT_CATEGORY_LIST);
        if (!StringUtils.isEmpty(categoryListRedisVal)) {
            productCategoryAllList = JSONArray.parseArray(categoryListRedisVal, ProductCategory.class);
        } else {
            String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/prodouctCategory/list", null, supplyApiConfig.getHeadsMap());
            JSONObject parseObject = JSON.parseObject(resultJson);
            if (parseObject == null || !"200".equals(parseObject.get("code").toString())) {
                throw new ApiException("接口调用出错");
            }
            productCategoryAllList = JSONArray.parseArray(parseObject.getString("data"), ProductCategory.class);
            redisService.set(RedisConstants.SUPPLY_CHAIN_PRODUCT_CATEGORY_LIST, JSONArray.toJSONString(productCategoryAllList));
            redisService.expire(RedisConstants.SUPPLY_CHAIN_PRODUCT_CATEGORY_LIST, 10 * 60);
        }
        return productCategoryAllList;
    }

    @Override
    public CommonResult getParentList(ProductCategoryRequest pcRequest) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/prodouctCategory/pageList", JSON.toJSONString(pcRequest), supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("渠道商接口异常");
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        return result;
    }

    @Override
    public CommonResult getChildrensById(ProductCategoryRequest pcRequest) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/prodouctCategory/getChildrensById", JSON.toJSONString(pcRequest), supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("渠道商接口异常");
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        return result;
    }

    @Override
    public CommonResult getBottomCategoryList(ProductCategoryRequest productCategoryRequest) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/prodouctCategory/getChildrensById", JSON.toJSONString(productCategoryRequest), supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            throw new ApiException("渠道商接口异常");
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        return result;
    }

    @Override
    public ProductSelectDetailResponse findProductSelectDetail(Integer productId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("id", productId.toString());
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/findProductSelectDetail", map, supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            return null;
        }
        JSONObject parse = JSON.parseObject(resultJson);
        ProductSelectDetailResponse productSelectDetailResponse = JSONObject.parseObject(parse.getString("data"), ProductSelectDetailResponse.class);
        List<ProductSpecResponse> spec = productSelectDetailResponse.getSpec();
        if (!CollectionUtils.isEmpty(spec)) {
            spec = spec.stream().sorted(Comparator.comparing(ProductSpecResponse::getSupplyPrice, Comparator.nullsFirst(Comparator.naturalOrder()))).collect(Collectors.toList());//供货价排序
            productSelectDetailResponse.setMinPrice(String.valueOf(spec.get(0).getSupplyPrice()));
            productSelectDetailResponse.setMaxPrice(String.valueOf(spec.get(spec.size() - 1).getSupplyPrice()));
        } else {
            productSelectDetailResponse.setMinPrice("0.00");
            productSelectDetailResponse.setMaxPrice("0.00");
        }
        //设置模板
        if (null != productSelectDetailResponse.getFreightId()) {
            HashMap<String, String> templateMap = new HashMap<>();
            templateMap.put("id", String.valueOf(productSelectDetailResponse.getFreightId()));
            log.info("查询供应链模板参数：{}", JSONUtil.toJsonStr(templateMap));
            String templateJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/freightTemplate/selectYxFreightTemplate", templateMap, supplyApiConfig.getHeadsMap());
            JSONObject templateParse = JSON.parseObject(templateJson);
            log.info("查询供应链模板返回：{}", templateParse);
            productSelectDetailResponse.setFreightTemplateStr(templateParse.getString("data"));
        }

        return productSelectDetailResponse;
    }

    private List<ProductSelectDetailResponse> findProductSelectDetailByIds(String productIds) {
        HashMap<String, String> map = new HashMap<>();
        map.put("ids", productIds);
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/findProductSelectDetailByIds", map, supplyApiConfig.getHeadsMap());
        if (StringUtils.isEmpty(resultJson)) {
            return null;
        }
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        List<ProductSelectDetailResponse> productSelectDetailResponses = new ArrayList<>();
        if (null != commonResult && 200 == commonResult.getCode()) {
            productSelectDetailResponses = JSONArray.parseArray(commonResult.getData().toString(), ProductSelectDetailResponse.class);
        }
        return productSelectDetailResponses;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveSelectedProducts(List<Integer> ids, String platformData, String shopId, List<String> provinceCodes) {
        shopId = Optional.ofNullable(shopId).orElse(supplyApiConfig.getShopId());
        if (StringUtils.isEmpty(platformData)) {
            throw new ApiException("渠道选择项不能为空！");
        }
        String[] shopIds = shopId.split(",");
        if (platformData.contains("all")) {
            platformData = "all";
        }
        if (shopId.contains("all")) {
            shopId = "all";
        }
        //1.处理当前平台
        if ("all".equals(shopId) || Arrays.stream(shopIds).anyMatch(e -> e.contains(supplyApiConfig.getShopId()))) {
            //选择的渠道集合
            List<String> platformDataList = new ArrayList<>();
            if ("all".equals(platformData)) {
                platformDataList.addAll(Lists.newArrayList(PlatformConstant.APP_PLATFORM, PlatformConstant.PLATFORM_H5, PlatformConstant.H5_2_PLATFORM, PlatformConstant.PROVINCE_PLATFORM, PlatformConstant.H5_3_PLATFORM));
            } else {
                platformDataList = Arrays.stream(platformData.split(",")).collect(Collectors.toList());
            }
            for (Integer supplyProductId : ids) {
                ProductSelectDetailResponse productSelectDetail = null;
                //1.2.1.查询供应链商品信息
                productSelectDetail = this.findProductSelectDetail(supplyProductId);
                if (productSelectDetail == null) {
                    throw new ApiException("商品不存在,请刷新重试");
                }
                List<ProductSkuKeyResponse> skuKey = new ArrayList<>();
                //商品详情图和轮播图
                List<ProductImgResponse> infoAndBanner = new ArrayList<>();
                List<ProductSpecResponse> spec = new ArrayList<>();
                //校验所选的渠道是否已存在商品
                ProductExample example = new ProductExample();
                example.createCriteria().andSupplyProductIdEqualTo(supplyProductId)
                        .andStatusIn(Arrays.asList(ProductStatusEnums.UP.getValue(), ProductStatusEnums.WAIT.getValue(), ProductStatusEnums.DOW.getValue()))
                        .andPlatformDataIn(platformDataList);
                List<Product> list = productMapper.selectByExample(example);
                List<String> syncPlatForm = new ArrayList<>();
                if (list.size() > 0) {
                    //当前商品已存的渠道，移除
                    List<String> exitPlat = list.stream().map(e -> e.getPlatformData()).collect(Collectors.toList());
                    syncPlatForm = platformDataList.stream().filter(item -> !exitPlat.contains(item)).collect(Collectors.toList());
//                    throw new ApiException(String.format("商品[%s]在 %s 渠道已存在, 请确认后再添加！", list.get(0).getProductName(), list.get(0).getPlatformData()));
                }else {
                    syncPlatForm = platformDataList;
                }
                spec = productSelectDetail.getSpec();
                skuKey = productSelectDetail.getSkuKey();
                infoAndBanner = productSelectDetail.getInfoList();
                infoAndBanner.addAll(productSelectDetail.getBannerList());

                //拉取商品的同时拉取运费模板
                FreightTemplateResponse oldFreightTemplate = freightTemplateService.selectBySupplyTemplateIdAndPlatformData(productSelectDetail.getFreightId(), platformData, 2);
                Integer freightId = platformData.equals("app") ? appDefaultTemplateId : h5DefaultTemplateId;
                if (null == oldFreightTemplate && null != productSelectDetail.getFreightId()) {
                    YxFreightTemplate yxFreightTemplate = JSONObject.parseObject(productSelectDetail.getFreightTemplateStr(), YxFreightTemplate.class);
                    if (yxFreightTemplate != null) {
                        yxFreightTemplate.setPlatformData(platformData);
                        yxFreightTemplate.setFreightType(2);
                        yxFreightTemplate.setSupplyTemplateId(productSelectDetail.getFreightId());
                        freightTemplateService.insertFreightTemplate(yxFreightTemplate);
                        freightId = yxFreightTemplate.getId();
                    }
                } else {
                    freightId = oldFreightTemplate.getId();
                }
                List<Boolean> resultFlag = new ArrayList<>();
                for (String pf : syncPlatForm) {
                    resultFlag.add(saveProduct(productSelectDetail, pf, freightId, skuKey, infoAndBanner, spec));
                }
                for (Boolean flag : resultFlag) {
                    if (!flag) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }
                }
            }
        }
        //2.处理其他平台，移除掉地区销售渠道，暂不处理。
        List<String> platformDataList = Arrays.stream(platformData.split(",")).collect(Collectors.toList());
        platformDataList.remove(PlatformConstant.PROVINCE_PLATFORM);
        String pt = String.join(",", platformDataList);
        sendAddProductMessage(ids, pt, shopId);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean selectAndAddToProvince(List<Integer> ids, String shopId, List<String> provinceCodes) {
        if (CollectionUtils.isEmpty(provinceCodes)) {
            throw new ApiException("请选择投放地区！");
        }
        String begin = supplyApiConfig.getShopId().substring(0, 5);
        String[] shopIds = StringUtils.isEmpty(shopId) ? new String[]{} : shopId.split(",");
        if (StringUtils.isEmpty(shopId) || ("all".equals(shopId) && Arrays.stream(shopIds).anyMatch(e -> e.contains(begin)))) {
            //选择的渠道集合
            List<String> platformDataList = new ArrayList<>();
            //销售渠道的地区
            for (String provinceCode : provinceCodes) {
                String province = PlatformConstant.PROVINCE_PLATFORM + provinceCode;
                platformDataList.add(province);
            }
            for (Integer productId : ids) {
                //查询商品当前信息
                Product product = productMapper.selectByPrimaryKey(productId);
                if (product == null) {
                    throw new ApiException("商品不存在,请刷新重试");
                }
                for (String provincePlatform : platformDataList) {
                    //校验地区是否已投放该商品，直接跳过
                    ProductExample example = new ProductExample();
                    example.createCriteria().andSupplyProductIdEqualTo(product.getSupplyProductId())
                            .andStatusIn(Arrays.asList(ProductStatusEnums.UP.getValue(), ProductStatusEnums.WAIT.getValue(), ProductStatusEnums.DOW.getValue()))
                            .andPlatformDataEqualTo(provincePlatform);
                    List<Product> list = productMapper.selectByExample(example);
                    if (list.size() > 0) {
                        continue;
                    }
                    List<ProductSpec> spec = productDao.getProductSpecInfo(productId);
                    List<ProductSkuKeyResponse> skuKey = goodsDao.findSku(productId);
                    ProductImgRequest productImgRequest = new ProductImgRequest();
                    productImgRequest.setProductId(productId);
                    List<ProductImg> infoAndBanner = productDao.getProductImgs(productImgRequest);
                    saveProductToProvince(product, provincePlatform, product.getFreightId(), skuKey, infoAndBanner, spec);
                }
            }
        } else {
            //跨平台同步暂不需要处理
        }
        return true;
    }

    @Override
    public List<SalesChannelsManagement> getProvinceByProductId(Integer id, Integer flag) {
        List<Product> products = productDao.getProductByBasicId(id, flag);
        SalesChannelsManagement request = new SalesChannelsManagement();
        request.setType(3);
        List<SalesChannelsManagement> allSalesChannels = salesChannelsManagementDao.getAllSalesChannels(request);
        Map<String, List<SalesChannelsManagement>> areaMap = allSalesChannels.stream().collect(Collectors.groupingBy(e -> PlatformConstant.PROVINCE_PLATFORM + e.getCode()));
        List<SalesChannelsManagement> result = new ArrayList<>();
        products.stream().forEach(e -> {
            List<SalesChannelsManagement> salesChannelsManagements = areaMap.get(e.getPlatformData());
            if (!CollectionUtils.isEmpty(salesChannelsManagements)) {
                result.add(salesChannelsManagements.get(0));
            }
        });
        return result;
    }

    public Boolean saveProduct(ProductSelectDetailResponse productSelectDetail, String platformData, Integer freightId, List<ProductSkuKeyResponse> skuKey, List<ProductImgResponse> infoAndBanner, List<ProductSpecResponse> spec) {
        List<Integer> addIds = new ArrayList<>();
        Product product1 = new Product();
        BeanUtils.copyProperties(productSelectDetail, product1);
        product1.setId(null);
        product1.setStatus((byte) 4);
        product1.setProductType(1);
        product1.setActivityType("");
        product1.setPlatformData(platformData);
        product1.setSupplyProductId(productSelectDetail.getId());
        product1.setVolume(StringUtils.isEmpty(product1.getVolumeStr()) ? 0 : parseInt(product1.getVolumeStr()));
        product1.setCreateTime(new Date());
        product1.setUpdateTime(null);
        //新增商品
        product1.setFreightId(freightId);
        productDao.insertEntity(product1);
        //保存成功则添加到集合
        if (product1.getId() != null) {
            addIds.add(productSelectDetail.getId());
        }

        //新增商品图片
        for (ProductImgResponse productImgResponse : infoAndBanner) {
            productImgResponse.setProductId(product1.getId());
        }
        if (!CollectionUtils.isEmpty(infoAndBanner)) {
            productImgDao.insertProductImgBatch(infoAndBanner);
        }

        //新增商品规格数据
        for (ProductSpecResponse productSpecResponse : spec) {
            productSpecResponse.setProductId(product1.getId());
            productSpecResponse.setSupplyId(productSpecResponse.getId());
        }
        if (!CollectionUtils.isEmpty(spec)) {
            productSpecDao.insertProductSpecBatch(spec);
        }

        //新增skuKey和skuKey_value
        for (ProductSkuKeyResponse productSkuKeyResponse : skuKey) {
            productSkuKeyResponse.setPid(product1.getId());
            productSkuKeyResponse.setSupplySkuKeyId(productSkuKeyResponse.getId());
            productSkuKeyResponse.setId(null);
            productSkuKeyDao.insertByEntity(productSkuKeyResponse);
            List<ProductSkuValueResponse> skuValue = productSkuKeyResponse.getSkuValue();
            if (productSkuKeyResponse.getId() != null) {
                for (ProductSkuValueResponse productSkuValueResponse : skuValue) {
                    productSkuValueResponse.setKid(productSkuKeyResponse.getId());
                    productSkuValueResponse.setPid(product1.getId());
                    productSkuValueResponse.setSupplySkuValueId(productSkuValueResponse.getId());
                    productSkuValueDao.insertByEntity(productSkuValueResponse);
                }
            }
        }

        return supplyProductReceive(addIds, platformData);
    }

    public void saveProductToProvince(Product product, String platformData, Integer freightId, List<ProductSkuKeyResponse> skuKey, List<ProductImg> infoAndBanner, List<ProductSpec> spec) {
        product.setId(null);
        product.setStatus((byte) 4);
//        product.setProductType(1);
//        product.setActivityType(product);
        product.setPlatformData(platformData);
        product.setVolume(StringUtils.isEmpty(product.getVolumeStr()) ? 0 : parseInt(product.getVolumeStr()));
        product.setCreateTime(new Date());
        product.setUpdateTime(null);
        //新增商品
        productDao.insertEntity(product);

        //新增商品图片
        for (ProductImg img : infoAndBanner) {
            img.setProductId(product.getId());
        }
        if (!CollectionUtils.isEmpty(infoAndBanner)) {
            productImgDao.insertImgBatch(infoAndBanner);
        }

        //新增商品规格数据
        for (ProductSpec productSpec : spec) {
            productSpec.setProductId(product.getId());
        }
        if (!CollectionUtils.isEmpty(spec)) {
            productSpecDao.insertSpecBatch(spec);
        }

        //新增skuKey和skuKey_value
        for (ProductSkuKeyResponse productSkuKeyResponse : skuKey) {
            productSkuKeyResponse.setSupplySkuKeyId(productSkuKeyResponse.getSupplySkuKeyId());
            productSkuKeyResponse.setPid(product.getId());
            productSkuKeyResponse.setId(null);
            productSkuKeyDao.insertByEntity(productSkuKeyResponse);
            List<ProductSkuValueResponse> skuValue = productSkuKeyResponse.getSkuValue();
            if (productSkuKeyResponse.getId() != null) {
                for (ProductSkuValueResponse productSkuValueResponse : skuValue) {
                    productSkuValueResponse.setKid(productSkuKeyResponse.getId());
                    productSkuValueResponse.setPid(product.getId());
                    productSkuValueDao.insertByEntity(productSkuValueResponse);
                }
            }
        }
    }

    public boolean supplyProductReceive(List<Integer> addIds, String platformData) {
        if (addIds.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("shopId", supplyApiConfig.getShopId());
            if (PlatformConstant.PLATFORM_H5.equalsIgnoreCase(platformData)) {
                map.put("shopId", h5ShopId);
            }
            if (PlatformConstant.APP_PLATFORM.equalsIgnoreCase(platformData)) {
                map.put("shopId", appShopId);
            }
            if (PlatformConstant.H5_2_PLATFORM.equalsIgnoreCase(platformData)) {
                map.put("shopId", h5_2ShopId);
            }
            if (PlatformConstant.H5_3_PLATFORM.equalsIgnoreCase(platformData)){
                map.put("shopId", h5_3ShopId);
            }
            if (platformData.contains(PlatformConstant.PROVINCE_PLATFORM)) {
                map.put("shopId", provinceShopId);
            }
            map.put("productIds", addIds);
            map.put("status", 1);
            String params = JSON.toJSONString(map);
            String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/receive", params, supplyApiConfig.getHeadsMap());
            if (StringUtils.isEmpty(resultJson) || !"200".equals(JSON.parseObject(resultJson).get("code").toString())) {
//             TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return false;
            }
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateproductDetail(Integer supplyProductId, String platformData) {
        //供应链商品详情
        ProductSelectDetailResponse productSelectDetail = this.findProductSelectDetail(supplyProductId);
        if (productSelectDetail == null || productSelectDetail.getId() == null) {
            throw new ApiException("供应链该商品不存在");
        }

        List<ProductSkuValueResponse> skuValue = new ArrayList<>();
        List<ProductSkuKeyResponse> skuKey = productSelectDetail.getSkuKey();
        List<ProductSpecResponse> spec = productSelectDetail.getSpec();
        List<Integer> specIdsFromChannel = spec.size() > 0 ? spec.stream().map(e -> e.getId()).collect(Collectors.toList()) : new ArrayList<>();
        List<Integer> skuKeyIdsFromChannel = skuKey.size() > 0 ? skuKey.stream().map(e -> e.getId()).collect(Collectors.toList()) : new ArrayList<>();
        for (ProductSkuKeyResponse item : skuKey) {
            skuValue.addAll(item.getSkuValue());
        }
        List<Integer> skuValueIdsFromChannel = skuValue.size() > 0 ? skuValue.stream().map(e -> e.getId()).collect(Collectors.toList()) : new ArrayList<>();

        //1.获取渠道现有的商品详情
        //1.1获取商品基本信息
        List<Product> products = productDao.selectBySupplyIdAndPlatformData(supplyProductId, platformData);
        if (products.size() == 0) {
            throw new ApiException("更新商品不存在");
        }

        //h5和app渠道都同时更新
        for (Product product : products) {
            //1.2商品规格相关的
            List<ProductSpec> localProductSpecs = productSpecDao.selectByProductIds(Arrays.asList(product.getId()));
            List<Integer> localSpecSupIds = localProductSpecs.size() > 0 ? localProductSpecs.stream().map(e -> e.getSupplyId()).collect(Collectors.toList()) : new ArrayList<>();

            //1.3商品sku-key
            List<ProductSkuKey> localProductSkuKeys = productSkuKeyDao.selectByPid(product.getId());
            List<Integer> localSkuKeySupsId = localProductSkuKeys.size() > 0 ? localProductSkuKeys.stream().map(e -> e.getSupplySkuKeyId()).collect(Collectors.toList()) : new ArrayList<>();

            //1.4商品sku-key-value
            List<ProductSkuValue> localProductSkuValues = productSkuValueDao.selectByPid(product.getId());
            List<Integer> localSkuValuesSupId = localProductSkuValues.size() > 0 ? localProductSkuValues.stream().map(e -> e.getSupplySkuValueId()).collect(Collectors.toList()) : new ArrayList<>();

            //2.对比并更新现在的商品数据
            //2.1---------更新商品基本信息
            Product upProduct = new Product();
            upProduct.setIsExit(productSelectDetail.getIsExit());
            upProduct.setMailNote(productSelectDetail.getMailNote());
            upProduct.setMailType(productSelectDetail.getMailType());
            upProduct.setTopCategoryId(productSelectDetail.getTopCategoryId());
            upProduct.setCategoryId(productSelectDetail.getCategoryId());
            upProduct.setBottomCategoryId(productSelectDetail.getBottomCategoryId());
            upProduct.setSupplyProductId(supplyProductId);
            upProduct.setId(product.getId());
            productDao.updateByEntity(upProduct);

            //2.2---------更新规格
            //2.2.1更新
            if (localSpecSupIds.size() != 0) {
                for (ProductSpecResponse e : spec) {
                    ProductSpecResponse entity = new ProductSpecResponse();
                    entity.setSupplyId(e.getId());
                    entity.setProductId(product.getId());
                    entity.setSalePrice(e.getSalePrice());
                    entity.setSupplyPrice(e.getSupplyPrice());
                    entity.setGoodsCode(e.getGoodsCode());
                    entity.setProImg(StringUtils.isEmpty(e.getProImg()) ? null : e.getProImg());
                    entity.setSkuSpec(StringUtils.isEmpty(e.getSkuSpec()) ? null : e.getSkuSpec());
                    productSpecDao.updateBySupEntity(entity);
                }
            }
            //2.2.1删除和新增
            //删除
            productSpecDao.deleteSpecsByParams(product.getId(), specIdsFromChannel);
            //新增
            if (localSpecSupIds.size() != 0) {
                //去掉specIdsFromChannel属于specIds的值
                List<Integer> list = specIdsFromChannel.stream().filter(t -> !localSpecSupIds.contains(t)).collect(Collectors.toList());
                List<ProductSpecResponse> collect = spec.stream().filter(t -> list.contains(t.getId())).collect(Collectors.toList());
                //新增商品规格数据
                for (ProductSpecResponse productSpecResponse : collect) {
                    productSpecResponse.setProductId(product.getId());
                    productSpecResponse.setSupplyId(productSpecResponse.getId());
                }
                if (collect.size() != 0) {
                    productSpecDao.insertProductSpecBatch(collect);
                }
            } else {//全部新增
                if (spec.size() != 0) {
                    for (ProductSpecResponse productSpecResponse : spec) {
                        productSpecResponse.setProductId(product.getId());
                        productSpecResponse.setSupplyId(productSpecResponse.getId());
                    }
                    productSpecDao.insertProductSpecBatch(spec);
                }
            }

            //2.3---------更新规格sku-key
            //2.3.1求交集-更新
            if (localSkuKeySupsId.size() != 0) {
                for (ProductSkuKeyResponse e : skuKey) {
                    ProductSkuKeyResponse enty = new ProductSkuKeyResponse();
                    enty.setName(e.getName());
                    enty.setPid(product.getId());
                    enty.setSupplySkuKeyId(e.getId());
                    enty.setUpdateTime(new Date());
                    productSkuKeyDao.updateBySupEntity(enty);
                }
            }
            //2.3.1求差集-删除和新增
            //删除
            if (localSkuKeySupsId.size() != 0) {
                productSkuKeyMapper.deleteSkuKeyByParams(product.getId(), skuKeyIdsFromChannel);
            }
            //新增
            if (localSpecSupIds.size() != 0) {
                //去掉skuKeyIdsFromChannel属于skuKeysId的值
                List<Integer> list = skuKeyIdsFromChannel.stream().filter(t -> !localSkuKeySupsId.contains(t)).collect(Collectors.toList());
                List<ProductSkuKeyResponse> collect = skuKey.stream().filter(t -> list.contains(t.getId())).collect(Collectors.toList());
                if (collect.size() != 0) {
                    //新增skuKey和skuKey_value
                    for (ProductSkuKeyResponse productSkuKeyResponse : collect) {
                        productSkuKeyResponse.setPid(product.getId());
                        productSkuKeyResponse.setSupplySkuKeyId(productSkuKeyResponse.getId());
                        productSkuKeyResponse.setId(null);
                        productSkuKeyDao.insertByEntity(productSkuKeyResponse);
                        List<ProductSkuValueResponse> skuValues = productSkuKeyResponse.getSkuValue();
                        if (productSkuKeyResponse.getId() != null) {
                            for (ProductSkuValueResponse productSkuValueResponse : skuValues) {
                                productSkuValueResponse.setKid(productSkuKeyResponse.getId());
                                productSkuValueResponse.setPid(product.getId());
                                productSkuValueResponse.setSupplySkuValueId(productSkuValueResponse.getId());
                                productSkuValueDao.insertByEntity(productSkuValueResponse);
                            }
                        }
                    }
                }
            } else {
                if (skuKey.size() != 0) {
                    //新增所有
                    //新增skuKey和skuKey_value
                    for (ProductSkuKeyResponse productSkuKeyResponse : skuKey) {
                        productSkuKeyResponse.setPid(product.getId());
                        productSkuKeyResponse.setSupplySkuKeyId(productSkuKeyResponse.getId());
                        productSkuKeyResponse.setId(null);
                        productSkuKeyDao.insertByEntity(productSkuKeyResponse);
                        List<ProductSkuValueResponse> skuValues = productSkuKeyResponse.getSkuValue();
                        if (productSkuKeyResponse.getId() != null) {
                            for (ProductSkuValueResponse productSkuValueResponse : skuValues) {
                                productSkuValueResponse.setKid(productSkuKeyResponse.getId());
                                productSkuValueResponse.setPid(product.getId());
                                productSkuValueResponse.setSupplySkuValueId(productSkuValueResponse.getId());
                                productSkuValueDao.insertByEntity(productSkuValueResponse);
                            }
                        }
                    }
                }
            }

            //2.4---------更新规格sku-key-value
            //2.4.1求交集-更新
            if (localSkuValuesSupId.size() != 0) {
                for (ProductSkuValueResponse e : skuValue) {
                    ProductSkuValueResponse enty = new ProductSkuValueResponse();
                    enty.setSupplySkuValueId(e.getId());
                    enty.setValue(e.getValue());
                    enty.setPid(product.getId());
                    productSkuValueDao.updateBySupEntity(enty);
                }
            }
            //2.4.1求差集-删除和新增
            //删除
            if (localSkuValuesSupId.size() != 0) {
                productSkuValueMapper.deleteSkuValueByParams(product.getId(), skuValueIdsFromChannel);
            }
        }

        return true;
    }

    @Override
    public CommonResult getProductPageList(ProductRequest product) {
        String param = JSON.toJSONString(product);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/product/all", param, supplyApiConfig.getHeadsMap());
        JSONObject parseObject = JSON.parseObject(resultJson);
        if (parseObject == null) {
            throw new ApiException("接口出错");
        } else if (!"200".equals(parseObject.get("code").toString())) {
            return JSONObject.parseObject(resultJson, CommonResult.class);
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        return result;
    }

    @Override
    public CommonResult create(ProductCategory productCategory) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/prodouctCategory/create", JSON.toJSONString(productCategory), supplyApiConfig.getHeadsMap());
        JSONObject parseObject = JSON.parseObject(resultJson);
        int i = 0;
        if (parseObject == null) {
            throw new ApiException("接口出错");
        } else if ("200".equals(parseObject.get("code").toString())) {
            //1.异步保存redis
            asyncServiceImpl.refreshRedisCategory();
            //1.新增本地分类数据
            //  如果没有选择父id 则默认为1级分类 “0”
            if (productCategory.getPid() == null) {
                productCategory.setPid(0);
            }
            //  默认下架
            if (productCategory.getStatus() == null) {
                productCategory.setStatus(SysConfigConstants.Category_Type.TYPE_2);
            }
            productCategory.setId(null);
            productCategory.setCreateTime(new Date());
            i = productCategoryMapper.insertSelective(productCategory);
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        if (result.getCode() == 200 && i == 1) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @Override
    public CommonResult update(ProductCategory productCategory) {
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/prodouctCategory/update", JSON.toJSONString(productCategory), supplyApiConfig.getHeadsMap());
        log.info("===resultJson==={}", resultJson);
        CommonResult commonResult = JSONObject.parseObject(resultJson, CommonResult.class);
        if (null == commonResult || 200 != commonResult.getCode()) {
            throw new ApiException("接口异常，请稍后重试:" + commonResult.getMessage());
        }
        String data = commonResult.getData().toString();
        log.debug("===data==={}", data);
        Integer dataInteger = Integer.parseInt(data);
        if (dataInteger <= 0) {
            return CommonResult.failed("修改失败");
        }

        //1.异步保存redis
        asyncServiceImpl.refreshRedisCategory();
        //2.更新本地分类表数据
        //如果Pid为0或者为空,则为一级分类
        if (!StringUtils.isEmpty(productCategory.getPid()) && productCategory.getPid() != 0) {
            //如果该分类状态改为上架,先查看上级分类是否是上架
        }

        // 如果没有选择父id 则默认为1级分类 “0”
        if (productCategory.getPid() == null) {
            productCategory.setPid(0);
        }
        productCategory.setUpdateTime(new Date());
        int i = productCategoryMapper.updateByPrimaryKeySelective(productCategory);

        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        if (result.getCode() == 200 && i == 1) {
            return CommonResult.success();
        } else {
            return CommonResult.failed("操作失败，请同步分类后再操作！");
        }
    }

    @Override
    public CommonResult delete(Integer id) {
        Map<String, String> params = new HashMap<>();
        params.put("id", id.toString());
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/prodouctCategory/delete", params, supplyApiConfig.getHeadsMap());
        JSONObject parseObject = JSON.parseObject(resultJson);
        int i = 0;
        if (parseObject == null) {
            throw new ApiException("接口出错");
        } else if ("200".equals(parseObject.get("code").toString())) {
            //1.异步保存redis
            asyncServiceImpl.refreshRedisCategory();
            //2.删除本地分类表数据
            i = productCategoryMapper.deleteByPrimaryKey(id);
        }
        CommonResult result = JSONObject.parseObject(resultJson, CommonResult.class);
        if (result.getCode() == 200 && i == 1) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @Override
    public void refreshProductCategory() {
        asyncServiceImpl.manualSynchronizationCategory();
    }

    @Override
    public List<Integer> getProductIds(Integer subjectId, Integer labelId, String platformData) {
        List<Integer> productIdList = new ArrayList<>();
        //判断商品专题是否为空
        if (null != subjectId) {
            ProductSubjectPlateExample productSubjectPlateExample = new ProductSubjectPlateExample();
            productSubjectPlateExample.createCriteria().andSubjectIdEqualTo(subjectId).andIsDeletedEqualTo(0);
            List<ProductSubjectPlate> productSubjectPlates = productSubjectPlateMapper.selectByExample(productSubjectPlateExample);
            if (!CollectionUtils.isEmpty(productSubjectPlates)) {
                List<Integer> productIds = productSubjectPlates.stream().map(ProductSubjectPlate::getProductId).collect(Collectors.toList());
                productIdList.addAll(productIds);
            }
        }

        //商品运营标签筛选
        if (null != labelId) {
            ChannelProductLabelExample cple = new ChannelProductLabelExample();
            cple.createCriteria().andLabelIdEqualTo(labelId).andChannelEqualTo(platformData);
            List<ChannelProductLabel> channelProductLabels = channelProductLabelMapper.selectByExample(cple);
            if (!CollectionUtils.isEmpty(channelProductLabels)) {
                List<Integer> productIds = channelProductLabels.stream().map(ChannelProductLabel::getProductId).collect(Collectors.toList());
                productIdList.addAll(productIds);
            }
        }

        if (!CollectionUtils.isEmpty(productIdList)) {
            List<Integer> collect = productIdList.stream().distinct().collect(Collectors.toList());
            return collect;
        }
        return new ArrayList<>();
    }

    @Override
    public List<Integer> getSupplyProductIds(Integer supplyProductLabelId) {
        //判断供应链标签是否为空
        List<Integer> supplyProductIds = new ArrayList<>();
        if (null != supplyProductLabelId) {
            //调用API查询使用该标签的商品id
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("productLabelId", supplyProductLabelId.toString());
            String result = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/getProductIdsByProductLabelId", paramMap, supplyApiConfig.getHeadsMap());
            supplyProductIds = JSONObject.parseArray(result, Integer.class);
        }
        return supplyProductIds;
    }

    @Override
    public List<Product> queryBySupplyIdAndPlatformData(List<Integer> supplyProductIds, List<String> platformData) {
        return productDao.queryBySupplyIdAndPlatformData(supplyProductIds, platformData);
    }

    public boolean sendAddProductMessage(List<Integer> ids, String platformData, String shopId) {
        com.ytjj.qmyx.admin.model.request.ChannelProductSelectRequest request = new com.ytjj.qmyx.admin.model.request.ChannelProductSelectRequest();
        request.setIds(ids);
        request.setPlatformData(platformData);
        request.setShopId(shopId);
        List<String> shopIdList = Lists.newArrayList(shopId.split(","));
        if (shopIdList.contains("all")) {
            SalesChannelsManagement management = new SalesChannelsManagement();
            management.setType(1);
            List<SalesChannelsManagement> allSalesChannels = salesChannelsManagementDao.getAllSalesChannels(management);
            shopIdList = allSalesChannels.stream().map(e -> e.getCode()).collect(Collectors.toList());
        }
        shopIdList.remove(supplyApiConfig.getShopId());
        request.setShopId(String.join(",",shopIdList));
        for (String id : shopIdList) {
            if (id.equals("GUOB004") || id.equals("GUOB005") || id.equals("GUOB006") || id.equals("GUOB007")) {
                guchuangRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_ADD_QUEUE, JSON.toJSONString(request));
            }
//            else if (id.equals("JUMD005") || id.equals("JUMD006") || id.equals("JUMD007") || id.equals("JUMD008")) {
//                jumaiduoRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_ADD_QUEUE, JSON.toJSONString(request));
//            } else if (id.equals("YQKJ006") || id.equals("YQKJ007") || id.equals("YQKJ008") || id.equals("YQKJ009")) {
//                yiquanRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_ADD_QUEUE, JSON.toJSONString(request));
//            } else if (id.equals("ZXLP005") || id.equals("ZXLP006") || id.equals("ZXLP007") || id.equals("ZXLP008")) {
//                zxlpRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_ADD_QUEUE, JSON.toJSONString(request));
//            } else if (id.equals("YGYX005") || id.equals("YGYX006") || id.equals("YGYX007") || id.equals("YGYX008") ) {
//                ygyxRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_ADD_QUEUE, JSON.toJSONString(request));
//            } else if (id.equals("YXHD005") || id.equals("YXHD006") || id.equals("YXHD007") || id.equals("YXHD008") ) {
//                yxhdRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_ADD_QUEUE, JSON.toJSONString(request));
//            } else if (id.equals("JCYX005") || id.equals("JCYX006") || id.equals("JCYX007") || id.equals("JCYX008") ) {
//                jckjRabbitTemplate.convertAndSend(QueueConstants.PRODUCT_ADD_QUEUE, JSON.toJSONString(request));
//            }
        }
        return true;
    }

    @Override
    public List<SalesChannelsManagement> getAllSalesChannels(SalesChannelsManagement request) {
        List<SalesChannelsManagement> salesChannelsManagements = salesChannelsManagementDao.getAllSalesChannels(request);
        return salesChannelsManagements;
    }

    @Override
    public AreaChannelsManagementResponse getSalesChannelsManagement(Integer status) {
        AreaChannelsManagementResponse response = new AreaChannelsManagementResponse();
        List<AreaChannelProductResponse> statisticsInfoForProvince = salesChannelsManagementDao.getStatisticsInfoForProvince(status);
        SalesChannelsManagementExample example = new SalesChannelsManagementExample();
        example.createCriteria().andIsAreaDefaultEqualTo(1).andTypeEqualTo(2).andStatusEqualTo(1);
        example.setOrderByClause("id desc");
        List<SalesChannelsManagement> salesChannelsManagements = salesChannelsManagementMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(salesChannelsManagements)) {
            throw new ApiException("未设置默认渠道，请务必设置！");
        }
        response.setProvinceList(statisticsInfoForProvince);
        response.setDefaultChannel(salesChannelsManagements.get(0));
        return response;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addOrUpdateArea(SalesChannelsManagement request) {
        Integer result = 0;
        try {
            if (null == request.getType()) {
                throw new ApiException("类型参数必传！");
            }
            //修改地区状态
            if (null != request.getId() && request.getType() == 3) {
                SalesChannelsManagement salesChannelsManagement = new SalesChannelsManagement();
                salesChannelsManagement.setId(request.getId());
                salesChannelsManagement.setStatus(request.getStatus());
                result = salesChannelsManagementMapper.updateByPrimaryKeySelective(salesChannelsManagement);
            } else if (null != request.getId() && request.getType() == 2) { //修改默认渠道
                SalesChannelsManagementExample example = new SalesChannelsManagementExample();
                example.createCriteria().andTypeEqualTo(2);
                SalesChannelsManagement salesChannelsManagement = new SalesChannelsManagement();
                salesChannelsManagement.setIsAreaDefault(0);
                int one = salesChannelsManagementMapper.updateByExampleSelective(salesChannelsManagement, example);
                if (one > 0) {
                    SalesChannelsManagement nowEntity = new SalesChannelsManagement();
                    nowEntity.setId(request.getId());
                    nowEntity.setIsAreaDefault(1);
                    int two = salesChannelsManagementMapper.updateByPrimaryKeySelective(nowEntity);
                    if (two <= 0) {
                        throw new ApiException("操作失败！");
                    }
                    result = 1;
                }
            } else if (null == request.getId()) {//新增地区
                SalesChannelsManagement nowEntity = new SalesChannelsManagement();
                if (StringUtils.isEmpty(request.getCode()) || StringUtils.isEmpty(request.getName())) {
                    throw new ApiException("code和name参数不能为空!");
                }
                nowEntity.setType(3);
                nowEntity.setName(request.getName());
                nowEntity.setStatus(0);
                nowEntity.setCode(request.getCode());
                result = salesChannelsManagementMapper.insertSelective(nowEntity);
            }
        } catch (DataIntegrityViolationException e) {
            throw new ApiException("当前地区已存在！");
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer copyProduct(Integer id) {
        Product oldProduct = productMapper.selectByPrimaryKey(id);
        if (!ObjectUtils.isEmpty(oldProduct)) {
            //新增商品主体
            Product newProduct = new Product();
            BeanUtils.copyProperties(oldProduct,newProduct);
            newProduct.setId(null);
            newProduct.setBankerColumnId(null);
            productDao.insertEntity(newProduct);
            //新增商品图片
            List<ProductImg> productImgs = productImgDao.queryProductImgInfo(oldProduct.getId());
            if (!CollectionUtils.isEmpty(productImgs)) {
                productImgs.stream().forEach(item->{
                    item.setId(null);
                    item.setProductId(newProduct.getId());
                });
                productImgDao.insertImgBatch(productImgs);
            }

            //新增商品规格数据
            List<ProductSpec> productSpecs = productSpecDao.selectByProductIds(Arrays.asList(oldProduct.getId()));
            if (!CollectionUtils.isEmpty(productSpecs)) {
                productSpecs.stream().forEach(item -> {
                    item.setId(null);
                    item.setProductId(newProduct.getId());
                });
                productSpecDao.insertSpecBatch(productSpecs);
            }
            //新增skuKey和skuKey_value
            List<ProductSkuKey> productSkuKeys = productSkuKeyMapper.queryProductSkuKeysByPid(oldProduct.getId());
            List<ProductSkuValue> productSkuValueList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(productSkuKeys)) {
                productSkuKeys.stream().forEach(item ->{
                    Integer kId = item.getId();
                    item.setId(null);
                    item.setPid(newProduct.getId());
                    productSkuKeyMapper.insertSelective(item);
                    List<ProductSkuValue> productSkuValues = productSkuValueMapper.queryProductSkuValuesByPidAndKid(oldProduct.getId(), kId);
                    if (!CollectionUtils.isEmpty(productSkuValues)) {
                        productSkuValues.stream().forEach(item2 ->{
                            item2.setId(null);
                            item2.setKid(item.getId());
                            item2.setPid(newProduct.getId());
                        });
                        productSkuValueList.addAll(productSkuValues);
                    }
                });
            }
            if (!CollectionUtils.isEmpty(productSkuValueList)) {
                productSkuValueMapper.insertProductSkuValueList(productSkuValueList);
            }
            return newProduct.getId();
        }
        return null;
    }
}
